package com.jing.ads.services;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Toast;

import com.jing.ads.R;
import com.jing.ads.activity.ActivityMain;
import com.jing.ads.activity.ActivityTest;
import com.jing.ads.application.MyApplication;
import com.jing.ads.log.Logger;
import com.jing.ads.util.GlobalUtil;
import com.jing.ads.util.PreferenceUtil;
import com.jing.ads.view.HandlerView;

public class BackgroudService extends Service implements View.OnTouchListener{

	public static final String ACTION_WINDOW_ADD = "com.jing.ads.service.action.add";
	public static final String ACTION_WINDOW_REMOVE = "com.jing.ads.service.action.remove";

	HandlerView myFV;
	WindowManager wm;
	WindowManager.LayoutParams wmParams = null;
	MyReceiver receiver;

	private boolean runDemon = true;

	WindowDemon demon;
	private float mTouchStartX;

	private float mTouchStartY;

	private float x;

	private float y;
	float rx, ry;

	int width, height;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		if (Logger.isDebug) {
//			Toast.makeText(this, "浮框服务启动", Toast.LENGTH_SHORT).show();
		}
		GlobalUtil.startDownloadService(this, this.getPackageManager());
		receiver = new MyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_WINDOW_ADD);
		filter.addAction(ACTION_WINDOW_REMOVE);
		this.registerReceiver(receiver, filter);
		demon = new WindowDemon();
		createView();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (receiver != null) {
			this.unregisterReceiver(receiver);
		}
		runDemon = false;
		if (myFV != null) {
			wm.removeView(myFV);
		}
		myFV = null;
	}

	class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_WINDOW_ADD.equals(action)) {
//				String ps = PreferenceUtil.getSharedString(context,
//						"push_setting", "y");
//				if (!ps.equals("y")) {
//					return;
//				}
				if (myFV == null) {
					recoveryWindow();
				}
			} else if (ACTION_WINDOW_REMOVE.equals(action)) {
				if (myFV != null) {
					wm.removeView(myFV);
				}
				myFV = null;
			}
		}
	}

	private void createView() {
		myFV = new HandlerView(this);

		wm = (WindowManager) getApplicationContext().getSystemService(
				WINDOW_SERVICE);
		width = wm.getDefaultDisplay().getWidth();
		height = wm.getDefaultDisplay().getHeight();
		int offset = wm.getDefaultDisplay().getHeight() / 5;
		wmParams = ((MyApplication) getApplication()).getMywmParams();
		wmParams.type = 2002;
		// wmParams.alpha = 100;
		wmParams.format = PixelFormat.TRANSPARENT;
		wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
		// wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL;
		int wO = (58 * width) / 480;
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;
		wmParams.x = 0;
		wmParams.y = offset - 10;
		wmParams.width = wO;
		wmParams.height = wO;
		wm.addView(myFV, wmParams);
		demon.start();
		myFV.setOnTouchListener(this);
	}

	private void updateViewPosition(boolean up) {
		int xo = (int) (x - mTouchStartX);
		int yo = (int) (y - mTouchStartY);
		wmParams.x = xo;
		wmParams.y = yo;
		if (up) {
			wmParams.x = (x >= width / 2) ? width : 0;
			wmParams.y = (int) ((y >= height - 200) ? height - 200 : y);
		}
		wm.updateViewLayout(myFV, wmParams);
	}

	private void recoveryWindow() {
		myFV = new HandlerView(this);
		if (wm == null) {
			wm = (WindowManager) getApplicationContext().getSystemService(
					WINDOW_SERVICE);
		}
		if (wmParams == null) {
			wmParams = ((MyApplication) getApplication()).getMywmParams();
		}
		myFV.setOnTouchListener(this);
		wm.addView(myFV, wmParams);
	}

	private void showWindow(boolean show) {
		if (show && myFV != null) {
//			PreferenceUtil.putSharedString(this, "push_setting", "y");
			return;
		}
		if (!show && myFV == null) {
//			PreferenceUtil.putSharedString(this, "push_setting", "n");
			return;
		}
		Intent i = new Intent();
		i.setAction(show ? ACTION_WINDOW_ADD : ACTION_WINDOW_REMOVE);
		sendBroadcast(i);
	}

	class WindowDemon extends Thread {

		@Override
		public void run() {
			while (runDemon) {
				try {
					if (GlobalUtil.isHome(BackgroudService.this)) {
						String y = PreferenceUtil.getSharedString(BackgroudService.this, "push_setting", "y");
						if (y.equals("y")) {
							showWindow(true);
						}else {
							showWindow(false);
						}
					}else {
						showWindow(false);
					}
					Thread.sleep(300);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int action = event.getAction();
		x = event.getRawX();
		y = event.getRawY();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			mTouchStartX = event.getX();
			mTouchStartY = event.getY();
			rx = event.getX();
			ry = event.getY();
			break;

		case MotionEvent.ACTION_MOVE:
			float zx = event.getX();
			float zy = event.getY();
			float mzx = Math.abs(rx - zx);
			float mzy = Math.abs(ry - zy);
			if (mzx >= 10 || mzy >= 10) {
				updateViewPosition(false);
			}
			break;

		case MotionEvent.ACTION_UP:
			float zzx = event.getX();
			float zzy = event.getY();
			float mmzx = Math.abs(rx - zzx);
			float mmzy = Math.abs(ry - zzy);
			if (mmzx >= 10 || mmzy >= 10) {
				updateViewPosition(true);
			} else {
				Intent i = new Intent(BackgroudService.this, ActivityMain.class);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(i);
//				Toast.makeText(ActivityTest.this, "show", 500).show();
			}
			rx = ry = 0;
			mTouchStartX = mTouchStartY = 0;
			break;

		}
		return true;
	}

}
